Convert Sorted Array to Binary Search Tree

Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.

Example 1:

Input: nums = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: [0,-10,5,null,-3,null,9] is also accepted:

Example 2:

Input: nums = [1,3]
Output: [3,1]
Explanation: [1,null,3] and [3,1] are both height-balanced BSTs.



Constraints:

  • 1 <= nums.length <= 10^4

  • -10^4 <= nums[i] <= 10^4

  • nums is sorted in a strictly increasing order.



My Solution

We can solve this with a binary search - like algorithm. We create a helper function that takes the array and start and end pointers as arguments. We then find the midpoint, create a TreeNode with it and recursively set end to mid-1 for the left subtree and start to mid+1 for the right subtree.

Time complexity would be O(n) since we visit all the elements of the input array. Space complexity is O(n) to create the BST.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        return helper(nums, 0, nums.length-1);
    }

    public TreeNode helper(int[] nums, int start, int end) {
        if (start > end) {
            return null;
        }

        int mid = start + (end-start)/2;

        TreeNode n = new TreeNode(nums[mid]);
        n.left = helper(nums, start, mid-1);
        n.right = helper(nums, mid+1, end);

        return n;
    }
}
Next
Next

Maximum Depth of Binary Tree